package com.sam.im.heiqun.utils;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.edmodo.cropper.CropImageView;
import com.sam.im.heiqun.R;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.GlideUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by wangguodong on 2017/9/29.
 */
public class ImageCropViewActivity extends BaseSwipeBackActivity {


    String TAG = "ImageCropViewActivity";

    //image_bit
    @BindView(R.id.image_bit)
    CropImageView image_bit ;
    @BindView(R.id.ok)
    TextView ok ;

    String path = "" ;
    int x = 0 ;
    int y = 0 ;
    int requestCode = 0 ;
    private String ALBUM_PATH = Environment.getExternalStorageDirectory() + "/a/";
    public static void start(Activity activity, String path, int x, int y, int requestCode){
        Intent intent = new Intent(activity, ImageCropViewActivity.class);
        intent.putExtra("path",path);
        intent.putExtra("x",x);
        intent.putExtra("y",y);
        intent.putExtra("requestCode", requestCode);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected String getTitleText() {
        return "图片裁切";
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {

        path = getIntent().getStringExtra("path");
        x = getIntent().getIntExtra("x",0);
        y = getIntent().getIntExtra("y",0);
        requestCode = getIntent().getIntExtra("requestCode",0);

        ok.setVisibility(View.VISIBLE);
        GlideUtils.loadImage(this,path,image_bit);

//        try {
//            image_bit.setFixedAspectRatio(true);
//            image_bit.setAspectRatio(x, y);
//
//            Bitmap bmp = BitmapFactory.decodeFile(path);//filePath
//
//            image_bit.setImageBitmap(bmp);
//        }catch (Exception e){
//            e.printStackTrace();
//        }

    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_image_crop_view;
    }


    @OnClick({R.id.ok, R.id.pre_v_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.pre_v_back:
                finish();
                break;
            case R.id.ok:
                try {

                    File dirFile = new File(path);
                    Bitmap bm = BitmapFactory.decodeFile(path);
                    image_bit.setImageBitmap(bm);
                    Bitmap croppedImage = image_bit.getCroppedImage3(bm);

                    if (null!=croppedImage){
                        ToolsUtils.saveBitmapToSdCard(this,bm,path);
                    }else {
                        Log.i("-----", "onClick: ============剪切的图片为空啊=============");
                    }
                }catch (Exception e){
                    Log.e(TAG,"yichang  " +e.getMessage());
                    Log.e(TAG,"yichang  " +e.getStackTrace());
                    e.printStackTrace();
                    showToast("图片剪切失败！");
                }
                setResult(RESULT_OK, new Intent());
                finish();
                break;
        }
    }

    private Bitmap zoomBitmap(Bitmap bitmap, float vw, float vh) {
        float width = bitmap.getWidth();//获得图片宽高
        float height = bitmap.getHeight();

        float scaleWidht, scaleHeight, x, y;//图片缩放倍数以及x，y轴平移位置
        Bitmap newbmp = null; //新的图片
        Matrix matrix = new Matrix();//变换矩阵
        if ((width/height)<=vw/width){//当宽高比大于所需要尺寸的宽高比时以宽的倍数为缩放倍数
            scaleWidht = vw / width;
            scaleHeight = scaleWidht;
            y = ((height*scaleHeight - vh) / 2)/scaleHeight;// 获取bitmap源文件中y做表需要偏移的像数大小
            x = 0;
        }else {
            scaleWidht = vh / height;
            scaleHeight = scaleWidht;
            x = ((width*scaleWidht -vw ) / 2)/scaleWidht;// 获取bitmap源文件中x做表需要偏移的像数大小
            y = 0;
        }
        matrix.postScale(scaleWidht / 1f, scaleHeight / 1f);
        try {
            if (width - x > 0 && height - y > 0&&bitmap!=null)//获得新的图片 （原图，x轴起始位置，y轴起始位置，x轴结束位置，Y轴结束位置，缩放矩阵，是否过滤原图）为防止报错取绝对值
                newbmp = Bitmap.createBitmap(bitmap, (int) Math.abs(x), (int) Math.abs(y), (int) Math.abs(width - x),
                        (int) Math.abs(height - y), matrix, false);// createBitmap()方法中定义的参数x+width要小于或等于bitmap.getWidth()，y+height要小于或等于bitmap.getHeight()
        } catch (Exception e) {//如果报错则返回原图，不至于为空白
            e.printStackTrace();
            return bitmap;
        }
        return newbmp;
    }

    private BitmapFactory.Options getBitmapOption(int inSampleSize)

    {
        System.gc();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPurgeable = true;
        options.inSampleSize = inSampleSize;
        return options;
    }

    /** 保存方法 */
    public void saveBitmap(Bitmap bm) {
//        Log.e(TAG, "保存图片");
//        File f = new File("/sdcard/namecard/", picName);
        File f = new File(path);

        Bitmap oldBTM = BitmapFactory.decodeFile(path);//filePath
        String tempPath = "/storage/emulated/0/截屏/";
        if (f.exists()) {
            tempPath = tempPath + "aa.jpg";
            //f.delete();
        }
        if (null== f)f = new File(tempPath);
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 60, out);
            out.flush();
            out.close();
//            Log.i(TAG, "已经保存");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            try {
                FileOutputStream out = new FileOutputStream(f);
                oldBTM.compress(Bitmap.CompressFormat.PNG, 60, out);
                out.flush();
                out.close();
//            Log.i(TAG, "已经保存");
            } catch (Exception e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();

            }
        }

    }

}
